'use strict';
var _ = require('lodash');
var enums = require('../shared/enums.js');
module.exports = function(sequelize, DataTypes) {
  var order = sequelize.define('order', {
    id: {
      type: DataTypes.UUID,
      primaryKey: true,
      defaultValue: DataTypes.UUIDV1
    },
    num: DataTypes.STRING(13),
    status: {
      type: DataTypes.ENUM(enums.orderStatus),
      allowNull: false,
      defaultValue: 'unpaid',
      validate: {
        isIn: [enums.orderStatus]
      }
    },
    totalPrice: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0,
      validate: {
        isDecimal: true
      }
    },
    products: {
      type: DataTypes.BLOB,
      allowNull: false
    },
    address: DataTypes.BLOB,
    memo : DataTypes.STRING
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
      }
    },
    hooks: {
      beforeCreate: function(instance) {
        var timestampEncode = new Date().getTime().toString(31)
          .replace(/i/g, 'V')
          .replace(/j/g, 'W')
          .replace(/l/g, 'X')
          .replace(/o/g, 'Y');
        timestampEncode = timestampEncode.toUpperCase();
        var randomNum = _.padLeft(_.random(1, 9999), 4, '0');
        instance.num = timestampEncode + randomNum;
      }
    }
  });
  return order;
};
